<template>
    <div v-if="reciver" class="mainbox">
        <filePreviewPopModal @handleDelete="FileDelete" @handleModelClose="modelClose" @handlePreview="FilePreview"
            @handleFileSend="FileSend" style="min-width: 400px;
    width: 50%;" :file-list="fileList" :item="reciver" ref="sendpopCom"></filePreviewPopModal>
        <fileSendPopModal style="width: 100%; width: 80%;" :pre-view-item="preViewItem" ref="prepopCom">
        </fileSendPopModal>
        <div class="header">
            <Icon v-if="props.isMobile" class="spointer" @click="handleBack" name="back" size="24px" color="#ffffff">
            </Icon>
            <span style="font-size: 16px;cursor: pointer;">{{ reciver?.userName }}</span>
            <n-popselect v-model:value="chooseItem" :options="options" size="medium" scrollable>
                <Icon style="cursor: pointer;" name="more" size="24px" color="#ffffff"></Icon>
            </n-popselect>
        </div>
        <div style="width: 100%;flex:1">
            <n-split direction="vertical" :on-update:size="sizeChange" :max="0.65" :min="0.45" :default-size="0.65"
                style="height: 100%">
                <template #1>
                    <div @scroll="handleScroll" :style="{
                        height: autoYHeight + 'px',
                    }" class="messagebox" ref="messageBoxRef">



                        <!-- <div v-if="loadingLock" style="width: 100%;display: flex;justify-content: center;flex-direction: row-reverse;height: 30px;align-items: center;">加载中...</div> -->
                        <Message ref="msgCom" @handlePreview="FilePreview" @handleDownload="FileDownload"
                            :msglist="props.msglist" :friendlistData="props.friendlistData">
                        </Message>
                        <div v-if="loadingLock"
                            style="transform: rotate(180deg);width: 100%;display: flex;justify-content: center;height: 30px;position: sticky;bottom: 0; align-items: center;flex-direction: row-reverse;">
                            ...加载中,请耐心等待</div>


                    </div>
                </template>
                <template #2>
                    <div class="tools">
                        <div style="display: flex;align-items: center;">
                            <n-space>
                                <n-popover trigger="click">
                                    <template #trigger>
                                        <div>
                                            <Icon style="cursor: pointer;" name="meme" size="24px" color="#888"></Icon>
                                        </div>

                                    </template>
                                    <Picker :data="emojiIndex" :emojiSize="18" :showSearch="false" :showPreview="false"
                                        :infiniteScroll="false" :i18n="emojiI18n" set="apple" @select="handleEmoji" />
                                </n-popover>

                                <n-upload :show-file-list="false" multiple :custom-request="() => { }"
                                    @change="customRequest">
                                    <Icon style="cursor: pointer;" name="file" size="24px" color="#888"></Icon>
                                </n-upload>

                                <Icon style="cursor: pointer;" name="message1" size="24px" color="#888"></Icon>
                            </n-space>

                        </div>
                        <div style="display: flex;align-items: center;">
                            <n-space>
                                <Icon style="cursor: pointer;" name="email" size="22px" color="#888"></Icon>
                                <Icon style="cursor: pointer;" name="audio" size="27px" color="#888"></Icon>
                                <Icon style="cursor: pointer;" name="video" size="24px" color="#888"></Icon>
                            </n-space>
                        </div>
                    </div>
                    <div class="textareabox">
                        <n-input class="textarea" @keyup.enter.exact="sendMsg" v-model:value="textarea" type="textarea"
                            placeholder="请输入要发送的内容" />
                        <n-button class="sendbtn" @click.stop="sendMsg" type="primary">发送</n-button>
                    </div>

                </template>
            </n-split>
        </div>
    </div>
    <div class="nullstyle" v-else>
        <img src="../assets/null.png" alt="" srcset="">
    </div>
</template>

<script setup lang="ts">
import "emoji-mart-vue-fast/css/emoji-mart.css";
import { Picker } from "emoji-mart-vue-fast/src";
import { ref, getCurrentInstance, onMounted, onBeforeUnmount } from 'vue'
import Icon from './Icon.vue'
import Message from './message.vue'
import storage from '@/utils/storage'
import { emojiI18n, options, emojiIndex } from '@/utils/constData'
import { getFileExtension, determineFileType, createBlob, getVideoBobUrl, debounce } from '@/utils/common'
import filePreviewPopModal from "./filePreviewPopModal.vue";
import fileSendPopModal from "./fileSendPopModal.vue";
import { createDiscreteApi } from 'naive-ui'
import { upload } from '@/api/chat'
const { message, notification } = createDiscreteApi(
    ['message', 'dialog', 'notification', 'loadingBar', 'modal']
)


const props = defineProps({
    isMobile: {
        type: Boolean,
        default: false,
    },
    loadingLock: {
        type: Boolean,
        default: false,
    },
    msglist: {
        type: Array,
        default: () => [],
    },
    friendlistData: {
        type: Array,
        default: () => [], 
    },
    reciver: {
        type: Object,
        default: () => ({}),
    },
})

const messageBoxRef = ref<HTMLElement | null>(null);
const reverseScroll = (event: any) => {
    event.preventDefault(); // 阻止默认滚动行为

    if (messageBoxRef.value) {
        // 反转滚动的方向
        messageBoxRef.value.scrollTop -= event.deltaY;

    }
};

onMounted(() => {
    // 确保scrollContainer已经挂载并获取到真实的DOM元素
    if (messageBoxRef.value) {
        messageBoxRef.value.addEventListener('wheel', reverseScroll, { passive: false });
    }
});

onBeforeUnmount(() => {
    // 清理事件监听器以避免内存泄漏
    if (messageBoxRef.value) {
        messageBoxRef.value.removeEventListener('wheel', reverseScroll);
    }
});

const solidedown = async () => {
    const container = messageBoxRef.value as HTMLElement;
    container.scrollTop -= 1
}
const handleScroll = debounce(() => {
    const container = messageBoxRef.value;
    if (!container) return;
    const threshold = 30; // 增加阈值以避免过早触发
    const isNearBottom =
        container.scrollHeight - container.scrollTop - container.clientHeight <= threshold;

    if (isNearBottom && !props.loadingLock) {
        emits('ScrollToTop', (props.msglist as any)[props.msglist.length - 1].time);
    }
}, 300); // 减少防抖时间以提高响应速度


const autoYHeight = ref<number>(0);
const sizeChange = (e: any) => {
    let autoHeight = window.innerHeight - 70;
    autoYHeight.value = autoHeight * +e;

};
window.addEventListener('resize', () => {
    init()
})
const FileDownload = async (url: any, filename: any) => {
    proxy.$refs.msgCom.btnLoading = true

    try {
        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/octet-stream'
            }
        });
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const blob = await response.blob();
        if (blob) {
            proxy.$refs.msgCom.btnLoading = false

            // 创建一个 a 标签并触发点击事件来下载文件
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = filename;
            link.click();

            // 清理
            URL.revokeObjectURL(link.href);
        }

    } catch (error) {
        console.error('Error downloading file:', error);
        // 可以在这里添加额外的错误处理逻辑
    }
}
const IuploadFile = () => {
    return new Promise((resolve, reject) => {
        const formdata = new FormData();
        for (const item of fileList.value) {
            formdata.append("wxfile", item.file.file);
        }
        upload(formdata).then((res: any) => {
            if (res.code == 200) {
                let data = res.data;
                resolve(data);
            } else {
                reject(res);
            }
        })
    });
};
const { proxy } = getCurrentInstance() as any


const handleEmoji = (emoji: any) => {
    textarea.value += emoji.native;
}
const chooseItem = ref<string>("")
const textarea = ref<any>("")
const fileList = ref<any>([])
const customRequest = async ({ file }: { file: any }) => {
    let res = createBlob(file.file);
    let ext = getFileExtension(file.name);
    let { icon, type } = determineFileType(ext, res);
    var obj = {};
    if (type == "video") {
        let ress = await getVideoBobUrl(res);
        obj = {
            file: file,
            blobUrl: res,
            preicon: ress,
            type: type,
        };
    } else {
        obj = {
            file: file,
            blobUrl: res,
            preicon: icon,
            type: type,
        };
    }
    fileList.value.push(obj);
    proxy.$refs.sendpopCom.modalShow = true;
};
const emits = defineEmits(['back', 'sendMsg', 'ScrollToTop', 'ScrollToTopReset'])
const handleBack = () => {
    emits('back')
}
const sendLock = ref<boolean>(false)
const sendMsg = () => {
    if (!textarea.value) {
        notification.info({
            content: "请先输入内容",
        });
        return;
    }
    if (textarea.value.length > 500) {
        notification.info({
            content: "内容过长，请重新输入或者分段发送",
        });
        return;
    }
    if (sendLock.value == true) {
        notification.info({
            content: "请稍后重试",
        });
        return;
    } else {
        sendLock.value = true;
        let obj = {
            tid: props.reciver._id,
            fid: storage.get("userinfo")._id,
            time: new Date().getTime(),
            type: "text",
            content: textarea.value,
            opType: "msg",
        };

        emits('sendMsg', { type: "message", data: obj })
        setTimeout(() => {
            sendLock.value = false;
        }, 1000);
    }

    textarea.value = "";
}
const modelClose = () => {
    proxy.$refs.sendpopCom.fileText = "";
    proxy.$refs.sendpopCom.uploadLoading = false;
    fileList.value = [];
}



const init = () => {
    if (!props.reciver) {
        return;
    }
    let autoHeight = window.innerHeight - 70;
    autoYHeight.value = autoHeight * 0.65;


}
init()
const preViewItem = ref<any>({})

const FileDelete = (e: any) => {
    fileList.value.splice(e, 1);
    if (fileList.value.length == 0) {
        proxy.$refs.sendpopCom.modalShow = false;
    }
};


const FilePreview = (e: any, type?: any) => {

    if (!type) {
        preViewItem.value = e;
    } else {
        preViewItem.value = {
            type: e.type,
            blobUrl: e.content,
        };
    }
    proxy.$refs.prepopCom.modalShow = true;
}
const FileSend = (sprops: any) => {
    if (!proxy.$refs.sendpopCom.uploadLoading) {
        proxy.$refs.sendpopCom.uploadLoading = true;
        IuploadFile()
            .then((res: any) => {

                let lists = res;
                lists = lists.map((e: any) => {
                    return {
                        ...e,
                        type: determineFileType(getFileExtension(e.name), "url").type,
                    };
                });
                for (let list of lists) {
                    let obj = {
                        tid: props.reciver._id,
                        fid: storage.get("userinfo")._id,
                        time: new Date().getTime(),
                        type: list.type,
                        content: list.url,
                        opType: "file",
                        remark: list.name,
                    };

                    emits('sendMsg', { type: "message", data: obj })
                }
            })
            .catch((err: any) => {
                if (err.code == 202) {
                    message.error("文件过大");
                }
            })
            .finally(() => {
                proxy.$refs.sendpopCom.modalShow = false;
                if (sprops.fileText) {
                    let obj = {
                        tid: props.reciver._id,
                        fid: storage.get("userinfo")._id,
                        time: new Date().getTime(),
                        type: "text",
                        content: sprops.fileText,
                        opType: "msg",
                    };
                    emits('sendMsg', { type: "message", data: obj })
                    proxy.$refs.sendpopCom.fileText = "";
                }
                proxy.$refs.sendpopCom.uploadLoading = false;
            });
    }
};
defineExpose({
    solidedown

})
</script>

<style lang="scss" scoped>
:deep(.n-input-wrapper) {
    resize: none !important;
}

.spointer {
    cursor: pointer;
}

.messagebox {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    position: relative;
    overflow-y: scroll;
    transform: rotate(180deg);
    direction: rtl;
    // padding-bottom: 20px;
    box-sizing: border-box;
    background: #f5f5f5;
    scroll-behavior: smooth;
    -webkit-overflow-scrolling: touch;
}

.nullstyle {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f5f5;

    img {
        width: 50%;
        border-radius: 10px;
    }
}

.mainbox {
    width: 100%;
    height: 100%;
    background: #f5f5f5;
    display: flex;
    flex-direction: column;

    .header {
        height: 70px;
        width: 100%;
        flex-shrink: 0;
        background: #085ffa;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 20px;
        box-sizing: border-box;
    }

    .tools {
        width: 100%;
        height: 40px;
        background: #f5f5f5;
        display: flex;
        align-items: center;
        box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.1);
        padding: 0 20px;
        box-sizing: border-box;
        justify-content: space-between;
    }

    .textareabox {
        width: 100%;
        height: calc(100% - 40px);
        position: relative;
        background: #f5f5f5;

        .textarea {
            width: 100%;
            height: 100%;
            background: #f5f5f5;
        }

        .sendbtn {
            position: fixed;
            bottom: 10px;
            right: 10px;
        }
    }
}
</style>